<template>
  <div id="mail-content-host"></div>
</template>

<script setup name="MailContent">
import { onMounted, watch } from 'vue'
import { parse } from 'node-html-parser'

// 定义 props
const props = defineProps({
  htmlContent: {
    type: String,
    required: true
  }
})

// 获取组件的根元素
let host

// 附加 Shadow DOM 并初始化内容
const attachShadowDOM = () => {
  host = document.getElementById('mail-content-host')
  const shadowRoot = host.attachShadow({ mode: 'open' })

  // 创建内容元素
  const contentElement = document.createElement('div')
  contentElement.innerHTML = processHtmlContent(props.htmlContent)

  // 将样式和内容添加到 Shadow DOM
  shadowRoot.appendChild(contentElement)
}

// 监听 htmlContent 的变化并更新 Shadow DOM
const updateShadowDOM = () => {
  const shadowRoot = host.shadowRoot
  const contentElement = shadowRoot.querySelector('div')
  if (contentElement) {
    contentElement.innerHTML = processHtmlContent(props.htmlContent)
  }
}

const processHtmlContent = (htmlContent) => {
  const root = parse(htmlContent)
  root.querySelectorAll('a').forEach((a) => {
    a.setAttribute('target', '_blank')
  })
  return root.toString()
}

onMounted(() => {
  attachShadowDOM()
})

watch(
  () => props.htmlContent,
  (newContent, oldContent) => {
    if (newContent !== oldContent) {
      updateShadowDOM()
    }
  }
)
</script>
